package ccnu.agile.service.impl;

import ccnu.agile.service.ITokenService;
import ccnu.agile.utils.JSONUtils;
import ccnu.agile.utils.LogUtils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Map;

/**
 * @Description: JSON Web Token 颁发/校验服务类
 * @Author: JreamY
 * @Date: 2021/10/22
 **/
@Service("jwtokenService")
public class JWTokenServiceImpl implements ITokenService {

    /**
     * 用于JWT进行签名加密的秘钥
     */
    private static String SECRET = "@welcome-to-capd!";

    @Override
    public String generate(Map<String, String> map) {

        LogUtils.info(this, "generate token map: {}", JSONUtils.toJSON(map));

        JWTCreator.Builder builder = JWT.create();
        // 将map内的信息传入JWT的payload中
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });

        // 设置JWT令牌的过期时间为60
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, 1800);
        builder.withExpiresAt(instance.getTime());

        // 设置签名并返回token
        return builder.sign(Algorithm.HMAC256(SECRET));
    }


    @Override
    public void validate(String token) {
        getClaims(token);
    }


    @Override
    public Map<String, Claim> getClaims(String token) {

        DecodedJWT jwt = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return jwt.getClaims();
    }

    @Override
    public <T> T getValue(String token, String param, Class<T> clazz) {

        Map<String, Claim> claimMap = getClaims(token);
        Claim claim = claimMap.get(param);
        return claim == null ? null : claim.as(clazz);
    }

}
